package com.sunshine.androidjavapractise.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.sunshine.androidjavapractise.R;
import com.sunshine.androidjavapractise.ui.activity.MessageActivity;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import static com.sunshine.androidjavapractise.ui.activity.CustomActivity.startPollingservice;

public class PollingService extends Service {
    private Notification mNotification;
    private NotificationManager mNotificationManager;
    private Executor mExecutor;

    public PollingService() {
        mExecutor = Executors.newScheduledThreadPool(4);
        System.out.println("PollingService");
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("onStartCommand");
        initNotificationManager();
        startPollingservice(this, 1, PollingService.class);
        mExecutor.execute(mRunnable);
        return super.onStartCommand(intent, flags, startId);
    }

    int count = 0;


    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            long threadId = Thread.currentThread().getId();

            System.out.println("polling... count = " + count + " threadId = " + threadId);
            count++;
            if (2 == count % 3) {
                System.out.println("New message");
                showNotification();
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void initNotificationManager() {
        if (null == mNotificationManager) {
            mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        }

        if (null == mNotification) {
            int icon = R.drawable.ic_dialog_closed;
            Notification.Builder builder = new Notification.Builder(this);
            builder.setSmallIcon(icon);
            Intent intent = new Intent(this, MessageActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(pendingIntent);
            builder.setTicker("test");
            builder.setContentText("new message");
            mNotification = builder.build();
            mNotification.contentIntent = pendingIntent;
        }

    }

    private void showNotification() {
        if (null != mNotification) {
            mNotification.when = System.currentTimeMillis();
            mNotificationManager.notify(0, mNotification);
        }
    }
}
